<?php
  // Separate game players by team and calculate maximum player
  // count by team and team total
  $team_players = array();
  $team_total = array();
  $max_player_count = 0;
  foreach ($game['teams'] as $team_id)
  {
    $team_players[$team_id] = array();
    $team_total[$team_id]  = 0;
    foreach ($game['points'] as $player_id => $point)
    {
      if ($players[$player_id]['team_id'] == $team_id)
      {
        $team_players[$team_id][] = $player_id;
        if ($point['summed'] == 'true')
          $team_total[$team_id] += $point['sum'];
      }
      if (($player_count = count($team_players[$team_id])) > $max_player_count)
        $max_player_count = $player_count;
    }
  }
?>

<?php $last_team_id = end($game['teams']) ?>
<table cellspacing="0" class="game">
  <tr>
<?php foreach ($game['teams'] as $team_id): ?>
    <th colspan="2" class="game"><?php echo $teams[$team_id]['name'] ?></th>
  <?php if ($team_id != $last_team_id): ?>
    <th class="separator">X</th>
  <?php endif; ?>
<?php endforeach; ?>
  </tr>

<?php for ($i=0; $i<$max_player_count; $i++): ?>
  <tr>
  <?php foreach ($game['teams'] as $team_id): ?>
    <?php $player_id = array_shift($team_players[$team_id]) ?>
    <?php if ($player_id == NULL): ?>
    <td class="gamePlayerName"></td>
    <td class="gamePlayerPoint"></td>
    <?php else : ?>
      <?php $point = $game['points'][$player_id] ?>
      <?php if ($point['summed'] == 'true'): ?>
    <td class="gamePlayerName"><?php echo $players[$player_id]['name'] ?></td>
    <td class="gamePlayerPoint"><?php echo $point['sum'] ?></td>
      <?php else: ?>
    <td class="gamePlayerIgnoredName"><?php echo $players[$player_id]['name'] ?></td>
    <td class="gamePlayerIgnoredPoint"><?php echo $point['sum'] ?></td>
      <?php endif; ?>
    <?php endif; ?>

    <?php if ($team_id != $last_team_id): ?>
    <td></td>
    <?php endif; ?>
  <?php endforeach; ?>
  </tr>
<?php endfor; ?>

  <tr>
<?php foreach ($game['teams'] as $team_id): ?>
    <td class="gameTotalText">Total</td>
    <td class="gameTotalSum"><?php echo $team_total[$team_id] ?></td>

  <?php if ($team_id != $last_team_id): ?>
    <td></td>
  <?php endif; ?>
<?php endforeach; ?>
  </tr>
</table>
